package com.markchu.web.system.controller;

import com.markchu.common.exception.ResultException;
import com.markchu.common.utils.ResultVoUtil;
import com.markchu.common.vo.ResultVo;
import com.markchu.component.fileUpload.FileUpload;
import com.markchu.component.fileUpload.enums.UploadResultEnum;
import com.markchu.modules.system.domain.Upload;
import com.markchu.modules.system.domain.User;
import com.markchu.modules.system.enums.FileTypeEnum;
import com.markchu.modules.system.service.UploadService;
import com.markchu.modules.system.service.UserService;
import com.markchu.web.structure.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * @author mark_chu
 * @date 2018/11/02
 */
@Controller
@RequestMapping("/home")
public class UploadController extends BaseController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private UserService userService;

    /**
     * 上传web格式图片
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public ResultVo uploadImage(Model model, @RequestParam("file") MultipartFile multipartFile, HttpServletResponse response) throws IOException {
        // 创建Upload实体对象
        ResultVo resultVo = new ResultVo();
        Upload upload = FileUpload.getFile(multipartFile, "/images");
        try {
            resultVo = saveImage(multipartFile, upload,"save");
        } catch (IOException | NoSuchAlgorithmException e) {
             System.out.println(ResultVoUtil.error("上传图片失败"));
        }
        Long imageId = 0L;
        if(!Objects.equals(resultVo.getData(),null)){
            imageId = ((Upload)resultVo.getData()).getId();
        }
        return resultVo;
    }

    /**
     * 上传web格式头像
     */
    @PostMapping("/upload/picture")
    @ResponseBody
    public ResultVo uploadPicture(@RequestParam("image") MultipartFile multipartFile) {

        // 创建Upload实体对象
        Upload upload = FileUpload.getFile(multipartFile, "/picture");
        try {
            return saveImage(multipartFile, upload,"thum");
        } catch (IOException | NoSuchAlgorithmException e) {
            return ResultVoUtil.error("上传头像失败");
        }
    }

    /**
     * 保存上传的web格式图片
     */
    private ResultVo saveImage(MultipartFile multipartFile, Upload upload,String opType) throws IOException, NoSuchAlgorithmException {
        // 判断是否为支持的图片格式
        String[] types = {
                "image/gif",
                "image/jpg",
                "image/jpeg",
                "image/png"
        };
        if(!FileUpload.isContentType(multipartFile, types)){
            throw new ResultException(UploadResultEnum.NO_FILE_TYPE);
        }

        // 判断图片是否存在
        Upload uploadSha1 = uploadService.getBySha1(FileUpload.getFileSha1(multipartFile));
        if (uploadSha1 != null) {
            if(Objects.equals(opType,"thum")){
                saveUserThum(uploadSha1);
            }
            return ResultVoUtil.success(uploadSha1);
        }

        FileUpload.transferTo(multipartFile, upload);
        // 将文件信息保存到数据库中
        upload.setFileType(FileTypeEnum.WEB.getCode());
        if(Objects.equals(opType,"save")){
            uploadService.save(upload);
        }else if(Objects.equals(opType,"thum")){
            saveUserThum(upload);
        }
        return ResultVoUtil.success(upload);
    }

    private void saveUserThum(Upload upload) {
        User user = getUserInfo();
        user.setPicture(upload.getUrl());
        userService.save(user);
    }

}
